package com.park.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayEcoMycarParkingVehicleQueryRequest;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.response.AlipayEcoMycarParkingVehicleQueryResponse;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.park.model.AlipayChargeInfo;
import com.park.model.Alipayinfo;
import com.park.model.Alipayrecord;
import com.park.model.Constants;
import com.park.model.Park;
import com.park.model.PosChargeData;
import com.park.model.Poschargemac;
import com.park.service.ActiveMqService;
import com.park.service.AlipayInfoService;
import com.park.service.AlipayrecordService;
import com.park.service.HardwareService;
import com.park.service.HttpUtil;
import com.park.service.JedisClient;
import com.park.service.ParkService;
import com.park.service.PosChargeDataService;
import com.park.service.PosChargeMacService;

@Controller
public class BarCodePayController {

	private static Log logger = LogFactory.getLog(BarCodePayController.class);

	public String APP_PRIVATE_KEY = Constants.alipayPrivateKey;
	public String ALIPAY_PUBLIC_KEY = Constants.alipayPublicKey;

	String URL = "https://openapi.alipay.com/gateway.do";
	String APP_ID = Constants.alipayAppId;
	String FORMAT = "json";
	String CHARSET = "UTF-8";
	String SIGN_TYPE = "RSA2";
	AlipayClient alipayClient = new DefaultAlipayClient(URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET,
			ALIPAY_PUBLIC_KEY, SIGN_TYPE);
	
	@Autowired
	PosChargeMacService poschargemacService;
	@Autowired
	PosChargeDataService poschargedataService;
	@Autowired
	HardwareService hardwareService;
	@Autowired
	AlipayrecordService alipayrecordService;
	@Autowired
	ParkService parkService;
	@Autowired
	AlipayInfoService alipayInfoService;
	@Autowired
	JedisClient jedisClient;
	

	@Value("#{prop.openDevice}")
	private String openDevice;
	
	@RequestMapping(value = "alipay/barcodepay/{mac}", method = RequestMethod.GET, produces = {
			"application/json;charset=UTF-8" })
	public String barcodepay(ModelMap modelMap, @PathVariable("mac") String mac,@RequestParam("auth_code") String auth_code) throws AlipayApiException{
		int macId=hardwareService.macToId(mac);
		List<Poschargemac> poschargemacs=poschargemacService.selectByMac(macId, 1);
		String poschargeid=jedisClient.get("out"+mac);
		
		if (poschargeid==null) {
			return "alipayh5/noRecord";
		}
		PosChargeData posChargeData=poschargedataService.getById(Integer.parseInt(poschargeid));
		String carNumber=posChargeData.getCardNumber();
		logger.info("auth_code数据为"+auth_code);
		
		posChargeData.setPosId(mac);
		poschargedataService.update(posChargeData);
		
		PosChargeData lastCharge =posChargeData;
		logger.info(posChargeData.getCardNumber()+"进行了支付宝扫码,开始处理,订单id:"+posChargeData.getId());
		AlipayClient alipayclientU = alipayClient;
		modelMap.addAttribute("charge", lastCharge.getChargeMoney());
		modelMap.addAttribute("enterDate",
				new SimpleDateFormat(Constants.DATEFORMAT).format(lastCharge.getEntranceDate()));
		if (lastCharge.getExitDate() == null) {
			lastCharge.setExitDate1(new Date());
		}
		long parkingDuration = (lastCharge.getExitDate().getTime() - lastCharge.getEntranceDate().getTime()) / 60000;
		modelMap.addAttribute("parkingDuration", parkingDuration);
		Park park = parkService.getParkById(lastCharge.getParkId());
		modelMap.addAttribute("parkName", park.getName());
		modelMap.addAttribute("chargeId", lastCharge.getId());
		modelMap.addAttribute("carNumber", carNumber);

		AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
		String out_trade_no = String.valueOf(posChargeData.getId());

		String total_amount = String.valueOf(lastCharge.getChargeMoney());
		request.setNotifyUrl("https://www.iotclouddashboard.com/park/alipay/barcodepay_notifyUrl");

		List<Alipayinfo> alipayinfos = alipayInfoService.getbyParkId(lastCharge.getParkId());
		if (!alipayinfos.isEmpty() && StringUtils.isNotEmpty(alipayinfos.get(0).getAppauthtoken())) {
			logger.info(carNumber + "使用appauthtoken" + alipayinfos.get(0).getAppauthtoken());
			request.putOtherTextParam("app_auth_token", alipayinfos.get(0).getAppauthtoken().trim());
		} else {

			alipayclientU = alipayClient;
			return "alipayh5/noRecord";
		}
		
		AlipaySystemOauthTokenRequest request4 = new AlipaySystemOauthTokenRequest();
		request4.setCode(auth_code);
		request4.setGrantType("authorization_code");
		AlipaySystemOauthTokenResponse oauthTokenResponse = null;
		try {
			oauthTokenResponse = alipayClient.execute(request4);
			logger.info("alipaytoken返回:"+oauthTokenResponse.getBody());
		} catch (AlipayApiException e) {
			// 处理异常
			e.printStackTrace();
		}
		String access_token = oauthTokenResponse.getAccessToken();
		String userId = oauthTokenResponse.getUserId();
		
		String serviceProvidedId=Constants.alipayAppId;
		request.setBizContent(
				"{" + "\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":" + total_amount + "," +

						"\"subject\":\"停车费-" + carNumber + "\"," +		
						"\"buyer_id\":\"" + userId + "\"," +	
						"\"extend_params\":{" + "\"sys_service_provider_id\":\""
						+ serviceProvidedId + "\"" + "}" +

						"}");

//设置sellerID
//		if (!alipayinfos.isEmpty() && StringUtils.isNotEmpty(alipayinfos.get(0).getAlipayid())) {
//			logger.info(carNumber + "使用pid:" + alipayinfos.get(0).getAlipayid());
//			request.setBizContent(
//					"{" + "\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":" + total_amount + "," +
//
//							"\"subject\":\"停车费-" + carNumber + "\"," + "\"seller_id\":\""
//							+ alipayinfos.get(0).getAlipayid() + "\"," +
//
//							"\"extend_params\":{" + "\"sys_service_provider_id\":\""
//							+ serviceProvidedId + "\"" + "}" +
//
//							"}");
//			
//			request.setBizContent("{" +
//					"\"out_trade_no\":\""+out_trade_no
//					
//				
//					+ "\"," +
//					"\"subject\":\""+posChargeData.getParkDesc()+posChargeData.getCardNumber()+"停车费"
//					+ "\"," +
//					"\"total_amount\":\""
//					+ total_amount +"\""+
//					"}");
//		}
		
		
		

		modelMap.addAttribute("outTradeNO", out_trade_no);
		
		modelMap.addAttribute("money", total_amount);

		AlipayTradeCreateResponse response = alipayclientU.execute(request);
		logger.info(carNumber + "支付宝订单报文:"+request.getBizContent()+ " 支付宝订单返回报文:" + response.getBody() + response.getSubMsg());
		modelMap.addAttribute("tradeNO", response.getTradeNo());

		Alipayrecord alipayrecord = new Alipayrecord();
		alipayrecord.setOutTradeNo(out_trade_no);
		alipayrecord.setAlitradeno(response.getTradeNo());
		alipayrecord.setPoschargeid(lastCharge.getId());
		alipayrecord.setDate(new Date());
		alipayrecord.setStatus("0");
		alipayrecordService.insertSelective(alipayrecord);

		return "alipayh5/index";
	}
	
	
	@RequestMapping(value = "alipay/barcodepay_notifyUrl", method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public String notifyUrl(HttpServletRequest request) {
		String trade_status = request.getParameter("trade_status");
		String trade_no = request.getParameter("trade_no");
		String receipt_amount = request.getParameter("receipt_amount");
		String out_trade_no = request.getParameter("out_trade_no");
		PosChargeData posChargeData=poschargedataService.getById(Integer.parseInt(out_trade_no));
		logger.info(posChargeData.getCardNumber()+" 接收到支付宝回调:" + out_trade_no);
		if (trade_status.equals("TRADE_SUCCESS")) {
			logger.info(posChargeData.getCardNumber()+"支付宝回调,参数:"+trade_no+receipt_amount+out_trade_no);
			posChargeData.setRejectReason(trade_no);
			posChargeData.setChargeMoney(Double.parseDouble(receipt_amount));
			posChargeData.setPaidMoney(Double.parseDouble(receipt_amount));
			posChargeData.setPaidCompleted(true);
			posChargeData.setPayType(0);
			poschargedataService.update(posChargeData);
			posChargeData.setPayType(10);
			Map<String,Object> args=new HashMap<>();
			args.put("mac", posChargeData.getPosId());
			args.put("plateNumber", posChargeData.getCardNumber());
			logger.info(posChargeData.getCardNumber()+"支付成功,开始执行开门命令!");
			HttpUtil.okHttpPost(openDevice,args);
			
		}
		return "ok";
	}
}
